/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Business.File;

import com.lowagie.text.DocumentException;
import com.sun.pdfview.PDFFile;
import java.awt.print.*;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xhtmlrenderer.pdf.ITextRenderer;


/**
 *
 * @author Domenico
 */
public class FacadeStampa {
//    private final String NOMEFILEHTML = "fattura.html";
//    private final String NOMEFILEPDF = "Fattura.pdf";
    
    private final String NOMEFATTURA = "fattura";
    private final String NOMEORDINEFORNITORE = "OrdineFornitoriFax";
    private final String ESTENSIONEHTML = ".html";
    private final String ESTENSIONEPDF = ".pdf";
    
//    private String percorsoFileHTML = null;
//    private String percorsoFilePDF = null;
    private String fontsDirectory = null;
    private String percorso = null;
    
    
    
    
    public  FacadeStampa() {
        String curDir = System.getProperty("user.dir");
//        percorsoFileHTML = curDir + "\\Fattura\\" + NOMEFILEHTML;
//        percorsoFilePDF = curDir + "\\Temp\\" + NOMEFILEPDF;    
        fontsDirectory = curDir + "\\Fonts\\";
        percorso = curDir + "\\Fattura\\";
        
    }
    public void stampaFattura() {
        stampaDocumentoHTML(NOMEFATTURA);
    }
    public void stampaOrdineFornitore() {
        stampaDocumentoHTML(NOMEORDINEFORNITORE);
    }
    public void stampaClienteFornitore() {
        stampaDocumentoHTML(Percorsi.PERCORSO_FILE_TEMPORANEI, Percorsi.CLIENTI_FORNITORI);
    }
    public void stampaDocumentoHTML(String percorsoFile, String NomeFile) {
        try {
            conversioneHTML_PDF(percorsoFile, NomeFile + Percorsi.ESTENSIONE_HTML);
            String percorsoFilePDF = percorsoFile + NomeFile + ESTENSIONEPDF;
            stampaPDF(percorsoFilePDF);
        } catch (IOException | PrinterException | DocumentException ex) {
            Logger.getLogger(FacadeStampa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void stampaDocumentoHTML(String NomeFile) {
        try {
            String percorsoFileHTML = percorso + NomeFile + ESTENSIONEHTML;
            conversioneHTML_PDF(percorsoFileHTML, NomeFile);
            String percorsoFilePDF = percorso + NomeFile + ESTENSIONEPDF;
             stampaPDF(percorsoFilePDF);
        } catch (IOException | PrinterException | DocumentException ex) {
            Logger.getLogger(FacadeStampa.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }
    //private void conversioneHTML_PDF(String PercorsoFile, String NomeFile) throws MalformedURLException, FileNotFoundException, DocumentException {
    //    String percorsoFileHTML = PercorsoFile + NomeFile;
        
    //}
    private void conversioneHTML_PDF(String PercorsoFile, String NomeFile) throws MalformedURLException, FileNotFoundException, DocumentException {
        
        String nomeSenzaEstensione = NomeFile.substring(0, NomeFile.lastIndexOf("."));
        String percorsoFilePDF = PercorsoFile + nomeSenzaEstensione + ESTENSIONEPDF;
        //String percorsoFileHTML = percorso + NomeFile + ESTENSIONEHTML;
        String percorsoFileHTML = PercorsoFile + NomeFile;
        
        File fileDaEliminare = new File(percorsoFilePDF); //Referenzia oggetto file da percorso
        if(fileDaEliminare.exists()) //se esiste...
        {
            fileDaEliminare.delete();
            fileDaEliminare = null;
        }
        //String inputFile = "C:\\fattura.html";
        //String outputFile = "C:\\Fattura.pdf";
        String url;
        
            url = new File(percorsoFileHTML).toURI().toURL().toString();
            OutputStream os = new FileOutputStream(percorsoFilePDF); 
            ITextRenderer renderer = new ITextRenderer();
            //renderer.getFontResolver().addFontDirectory(fontsDirectory, true);
            renderer.setDocument(url);
            renderer.layout();
            renderer.createPDF(os);
            renderer.finishPDF();
        
/*            
            // render

  BufferedImage buff = null;
//  buff = Graphics2DRenderer.renderToImage(percorsoFileHTML, "w3c-homepage.png", 1024);
  String address = new File(percorsoFileHTML).toURI().toURL().toString();
buff = Graphics2DRenderer.renderToImage(address, 800, 1024);

    File outputfile = new File("C:\\saved.png");
        try {
            ImageIO.write(buff, "png", outputfile);
        } catch (IOException ex) {
            Logger.getLogger(FacadeStampa.class.getName()).log(Level.SEVERE, null, ex);
        }
  */      
     }
    
    private void stampaPDF(String percorsoFilePDF) throws IOException, PrinterException {
        
        FileInputStream fis = null;
    
        String tempPercorsoFilePDF = generateName(percorsoFilePDF);
        copyFile(new File(percorsoFilePDF), new File(tempPercorsoFilePDF));
        // Create a PDFFile from a File reference
        //File f = new File(percorsoFilePDF);
        File f = new File(tempPercorsoFilePDF);
        
        fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        
       
        
        PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
        PDFPrintPage pages = new PDFPrintPage(pdfFile);
        
        // Create Print Job
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();

        Paper paper = new Paper();
        paper.setImageableArea(0,0,paper.getWidth(),paper.getHeight()); // no margin = no scaling
        pf.setPaper(paper);
            
        pjob.setJobName(f.getName());
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);
        
       

        
        
        if (pjob.printDialog()) {
            pjob.print();
        } 
        // Send print job to default printer
       fis.close();
        fc.close();
        f.delete();
        
        
   
    }
    public void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}
    private String generateName(String name){
        String newName = null;
        int i = 0;
        while (newName == null) {
            String tempName = name.substring(0, name.length() - 4) + i + ".pdf";
            File f = new File(tempName);
            if (f.exists()) {
                f.delete();
                i++;
            } else {
              newName = tempName;  
            }
        }
        return newName;
    }

    
}
